<template>
  <div class="container">
    <div class="app-container">
      <!-- 添加角色按钮 -->
      <el-button
        size="mini"
        type="primary"
        style="margin: 10px;"
        @click="visible = true"
      >添加角色</el-button>
      <!-- 表格里面数据 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="角色" align="center">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editList.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center">
          <template #default="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editList.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1 ? "启用" : "禁用" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editList.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" align="center">
          <template #default="{ row }">
            <!-- 分组标签 -->
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="update(row)">确定</el-button>
              <el-button size="mini" @click="cancel(row)">取消</el-button>
            </template>

            <template v-else>
              <el-button size="mini" type="text" @click="jurisdiction(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" style="margin-right: 10px;" @click="row.isEdit = true">编辑</el-button>

              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delrole(row.id)"
              >
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" justify="end">
        <el-col :span="null">
          <el-pagination
            layout="prev, pager, next,->"
            :total="pageData.total"
            :page-size="pageData.pagesize"
            :current-page="pageData.page"
            @current-change="pageChange"
          />
        </el-col>
      </el-row>
    </div>
    <!-- 新增角色弹框 -->
    <el-dialog title="新增角色" :visible.sync="visible" width="33%">
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" style="width: 90%;" size="mini" />
        </el-form-item>

        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="formData.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" style="width: 90%;" size="mini" />
        </el-form-item>

        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="submitBtn">确定</el-button>
              <el-button size="mini" @click="visible =false">取消</el-button>
            </el-col>
          </el-row>

        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限分配框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-tree
        ref="tree"
        :props="{label:'name'}"
        :data="treeList"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="permIds"
      />
      <span slot="footer" class="dialog-footer">
        <el-row type="flex" justify="center">
          <el-button size="mini" type="primary" @click="putRolePower">确 定</el-button>
          <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        </el-row>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleAPI, delRoleAPI, putRoleAPI, putRolePowerAPI, roleDetailAPI, roleListAPI } from '@/api/role'
import { permissionListAPI } from '@/api/permission'
import { tree2List } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      pageData: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      visible: false,
      dialogVisible: false,
      formData: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      treeList: [],
      permIds: []
    }
  },
  watch: {
    // 监听的 visible 的值变化是否重置表单
    visible(newValue) {
      if (!newValue) {
        this.$refs.formData.resetFields()
      }
    }
  },
  created() {
    this.roleList()
  },
  methods: {
    async roleList() {
      const res = await roleListAPI(this.pageData)
      // 把获取到数据赋值给 声明的变量
      this.pageData.total = res.data.data.total
      this.tableData = res.data.data.rows
      // 循环添加数据  isEdit 是打开编辑功能  editList 复制出另一份数据
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editList', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    pageChange(page) {
      // 把 pageChange 的内置方法获取到当前页数赋值给 page
      this.pageData.page = page
      this.roleList()
    },
    async submitBtn() {
      // 对表单进行校验
      this.$refs.formData.validate()
      // 调用新增员工接口
      const res = await addRoleAPI(this.formData)
      // 提示弹窗
      this.$message.success(res.data.message)
      // 关闭弹框
      this.visible = false
      // 刷新数据
      this.roleList()
    },
    cancel(row) {
      // 取消按钮： 重置表单里面数据
      row.editList = {
        name: row.name,
        state: row.state,
        description: row.description
      }

      row.isEdit = false
    },
    async update(row) {
      // 判断是否有角色名称
      if (!row.editList.name) {
        this.$message.warning('请输入角色名称')
        return
      }
      // 判断是否有角色描述
      if (!row.editList.description) {
        this.$message.warning('请输入角色描述')
        return
      }
      // 调用角色更新接口
      const res = await putRoleAPI({
        ...row.editList,
        id: row.id
      }, row.id)
      this.$message.success(res.data.message)
      // 合并对象 第二个参数之后的参数合并到第一个参数，相同数据后面的会覆盖前面的
      Object.assign(row, {
        ...row.editList,
        isEdit: false
      })
    },
    async delrole(id) {
      // 调用删除接口
      const res = await delRoleAPI(id)
      // 弹出提示框
      this.$message.success(res.data.message)
      // 判断当前页数是否是最后一条数据 是则减少一页
      if (this.tableData.length === 1) {
        this.pageData.page--
      }
      // 刷新页面数据
      this.roleList()
    },
    async jurisdiction(id) {
      this.dialogVisible = true
      // 渲染树
      const res1 = await permissionListAPI()
      this.treeList = tree2List(res1.data.data)
      // 获取角色详情
      const res2 = await roleDetailAPI(id)

      this.permIds = res2.data.data.permIds

      this.id = id
    },
    async putRolePower() {
      // 修改角色权限
      const res = await putRolePowerAPI({
        id: this.id,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      console.log(this.id, this.$refs.tree.getCheckedKeys())
      this.dialogVisible = false
      this.$message.success(res.data.message)
    }
  }
}
</script>
